# -*- utf-8 -*-
from ajson import aj

from config import Aliyun
import oss2
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest


def send_sms_code(code, phone):
    """发送验证码"""
    # 创建AcsClient实例

    client = AcsClient(Aliyun.AccessKey_ID, Aliyun.AccessKey_Secret, 'cn-hangzhou')

    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', "cn-hangzhou")
    request.add_query_param('PhoneNumbers', phone)
    request.add_query_param('SignName', "cacode")
    request.add_query_param('TemplateCode', "SMS_203180299")
    request.add_query_param('TemplateParam', aj.parse({
        'code': code
    }))
    response = client.do_action(request)
    # python2:  print(response)
    return response


def get_oss(bucket_name):
    # 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    auth = oss2.Auth(Aliyun.AccessKey_ID, Aliyun.AccessKey_Secret)
    # yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    # 填写Bucket名称。
    bucket = oss2.Bucket(auth, Aliyun.Endpoint, bucket_name)
    return bucket


def upload_img(bucket_name: str, filename: str, base64: bytes):
    """上传图片"""
    bucket = get_oss(bucket_name)
    # 填写Object完整路径和Bytes内容。Object完整路径中不能包含Bucket名称。
    result = bucket.put_object(filename, base64)
    return result


def delete_img(bucket_name, filenames: list):
    # -*- coding: utf-8 -*-
    bucket = get_oss(bucket_name)

    # 删除文件。<yourObjectName>表示删除OSS文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
    # 如需删除文件夹，请将<yourObjectName>设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
    response = bucket.batch_delete_objects(filenames)
    return response
